<?php

Yii::import('common.models._base.BaseClasses');

class Classes extends BaseClasses {

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function rules() {
        return array(
            array('class_titile,difficulty_type,classesTargetAudiences, class_description, class_short_description, class_tag, class_outcome, status, class_type_id,certificate, category_id,class_prerequisites', 'required'),
            array('status, users_id, class_type_id, difficulty_type, certificate, category_id, backend_user_id', 'numerical', 'integerOnly' => true),
            array('classesTargetAudiences', 'type', 'type' => 'array', 'allowEmpty' => false),
            array('class_titile', 'length', 'max' => 145),
            array('class_short_description', 'length', 'max' => 500),
            array('class_prerequisites, class_comment, create_time, update_time, class_other_information', 'safe'),
            array('class_prerequisites, class_comment, create_time, update_time, users_id, class_other_information, certificate, backend_user_id', 'default', 'setOnEmpty' => true, 'value' => null),
            array('id, class_titile, class_description, class_short_description, class_tag, class_outcome, class_prerequisites, class_comment, status, create_time, update_time, users_id, class_type_id, difficulty_type, class_other_information, certificate, category_id, backend_user_id', 'safe', 'on' => 'search'),
        );
    }

    public function attributeLabels() {
        return array(
            'id' => Yii::t('app', 'ID'),
            'class_titile' => Yii::t('app', 'Title'),
            'class_description' => Yii::t('app', 'Description'),
            'class_short_description' => Yii::t('app', 'Short Description'),
            'class_tag' => Yii::t('app', 'Class Tag'),
            'class_outcome' => Yii::t('app', 'Outcome'),
            'class_prerequisites' => Yii::t('app', 'Prerequisites'),
            'class_comment' => Yii::t('app', 'Comment'),
            'category_id' => 'Category',
            'classesTargetAudiences' => 'Target Audience',
        );
    }

    public function search() {
        $criteria = new CDbCriteria;
        $criteria->compare('id', $this->id, true);
        $criteria->compare('auth_key', $this->auth_key, true);
        $criteria->compare('class_titile', $this->class_titile, true);
        $criteria->compare('class_description', $this->class_description, true);
        $criteria->compare('class_short_description', $this->class_short_description, true);
        $criteria->compare('class_tag', $this->class_tag, true);
        $criteria->compare('class_outcome', $this->class_outcome, true);
        $criteria->compare('class_prerequisites', $this->class_prerequisites, true);
        $criteria->compare('class_comment', $this->class_comment, true);
        $criteria->compare('status', $this->status);
        $criteria->compare('create_time', $this->create_time, true);
        $criteria->compare('update_time', $this->update_time, true);
        $criteria->compare('users_id', $this->users_id);
        $criteria->compare('class_type_id', $this->class_type_id);
        $criteria->compare('difficulty_type', $this->difficulty_type);
        $criteria->compare('class_other_information', $this->class_other_information, true);
        $criteria->compare('certificate', $this->certificate);
        $criteria->compare('category_id', $this->category_id);
        $criteria->compare('backend_user_id', $this->backend_user_id, true);

        /* if($model->backend_user_id=="no"){
          $criteria->addCondition(array('condition'=>'backend_user_id is null'));
          } */


        /* $criteria->addCondition(array('condition'=>'backend_user_id is null')); */
        /* $criteria->addCondition(array('condition'=>'backend_user_id is not null')); */
        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    public static function deleteClassesTargetAudience($classId) {
        ClassesTargetAudience::model()->deleteAll('classes_id=:classes_id', array(':classes_id' => $classId));
    }

    public static function deleteClassesWithVenue($classId) {
        ClassWithVenue::model()->deleteAll('classes_id=:classes_id', array(':classes_id' => $classId));
    }

    public static function deleteClassesBatches($classId) {
        ClassBatch::model()->deleteAll('classes_id=:classes_id', array(':classes_id' => $classId));
    }

    public static function deleteClassesBatcheEarlyDiscount($classId) {
        ClassEarlyDiscount::model()->deleteAll('classes_id=:classes_id', array(':classes_id' => $classId));
    }

    public static function deleteClassesBatcheGroupDiscount($classId) {
        GroupDiscount::model()->deleteAll('classes_id=:classes_id', array(':classes_id' => $classId));
    }

    public static function deleteClassesBatcheSessions($classId) {
        BatcheSession::model()->deleteAll('classes_id=:classes_id', array(':classes_id' => $classId));
    }

    public static function deleteclassbatchweelymonthly($classId) {
        Classbatchweelymonthly::model()->deleteAll('classes_id=:classes_id', array(':classes_id' => $classId));
    }

    public static function deleteClassesStructure($classId) {
        ClassStructures::model()->deleteAll('classes_id=:classes_id', array(':classes_id' => $classId));
    }

    public static function classOtherInformation($classId) {
        $inormation = Classes::model()->findByPk($classId);
        return $inormation->class_other_information;
    }

    public static function deleteClassFunLearning($classId) {
        FunLearning::model()->deleteAll('classes_id=:class_id', array(':class_id' => $classId));
    }

    public static function deleteClassTicketBooked($classId) {
        TicketBooked::model()->deleteAll('classes_id=:classes_id', array(':classes_id' => $classId));
    }

    public static function getTargetAudience($model) {
        $audienceName = '';
        $targetAudience = ClassesTargetAudience::model()->findAll('classes_id=:classes_id', array(':classes_id' => $model->id));
        foreach ($targetAudience as $value) {
            $audienceNames = TargetAudience::model()->findByPk($value['target_audience_id']);
            $audienceName.=$audienceNames->target_audience_name . ', ';
        }
        return substr($audienceName, 0, -3);
    }

    public static function getclassWithVenues($classId) {
        $classWithVenue = ClassWithVenue::model()->findAll('classes_id=:classes_id', array(':classes_id' => $classId));
        return $classWithVenue;
    }

    public static function getClassBatch($classId, $venueId) {
        $classbatch = ClassBatch::model()->findAll('classes_id=:classes_id AND class_venue_id=:class_venue_id ', array(':classes_id' => $classId, 'class_venue_id' => $venueId));
        return $classbatch;
    }

    public static function getClassBatchEarlyBirdDiscount($classId, $bacthId) {
        $classEarlyDiscount = ClassEarlyDiscount::model()->findAll('classes_id=:classes_id AND class_batch_id=:class_batch_id ', array(':classes_id' => $classId, 'class_batch_id' => $bacthId));
        return $classEarlyDiscount;
    }

    public static function getClassBatchGroupDscount($classId, $bacthId) {
        $classGroupDiscount = GroupDiscount::model()->findAll('classes_id=:classes_id AND class_batch_id=:class_batch_id ', array(':classes_id' => $classId, 'class_batch_id' => $bacthId));
        return $classGroupDiscount;
    }

    public static function getCustomeSechedule($classId, $bacthId) {
        $customeSechedule = BatcheSession::model()->findAll('classes_id=:classes_id AND batche_id=:batche_id ', array(':classes_id' => $classId, 'batche_id' => $bacthId));
        return $customeSechedule;
    }

    public static function getSchedulename($scheduleId) {
        $name = ClassSchedule::model()->findByPk($scheduleId);
        echo $name->name;
    }

    public static function getClassStructure($classId, $bacthId) {
        $classStructure = ClassStructures::model()->findAll('classes_id=:classes_id AND class_batch_id=:class_batch_id ', array(':classes_id' => $classId, 'class_batch_id' => $bacthId));
        return $classStructure;
    }

    public static function getfunlearing($classId) {
        $funlearing = FunLearning::model()->find('classes_id=:classes_id', array(':classes_id' => $classId));
        return $funlearing;
    }

    public static function getclassWithImage($classId) {
        $classWithImage = ClassImage::model()->findAll('classes_id=:classes_id', array(':classes_id' => $classId));
        return $classWithImage;
    }

    public static function classImageingridView($data) {
        $userId = ($data->classes->backend_user_id != '') ? 'backend/' . getLoginUserId() : $data->classes->users_id;
        return ROOT_IMAGE_PATH.SkillConfig::getClassCourseImagethumbsPath($userId) . $data->photo;
    }

    public static function changeStatusIngridView($data) {
        return ($data->primary_image == 1) ? CHtml::image(baseUrl() . "/images/active.png", "Primary-image", array("title" => "Remove primary image", "style" => "cursor:pointer", "onclick" => "ChangeStatus(" . $data->id . ",$data->classes_id)")) : CHtml::image(baseUrl() . "/images/deactive.png", "Inactive", array("title" => "Mark Primary Image", "style" => "cursor:pointer", "onclick" => "ChangeStatus(" . $data->id . ",$data->classes_id)"));
    }

    public static function showUpdateButtion($data) {
        return ($data->backend_user_id != '') ? true : false;
    }

    public static function checkQueryEmpty($data) {
        $dataVal = MakeQuery::model()->findByAttributes(array('classes_id' => $data->id));
        return ($dataVal != '') ? CHtml::link('View Query', Yii::app()->createUrl('makeQuery/admin', array("classid" => $data->id))) : 'No Query';
    }

    public static function contentRate($data) {
        $dataVal = ClassCourseContentLikeUnlike::model()->findByAttributes(array('classes_id' => $data->id));
        return (!empty($dataVal)) ? CHtml::link('Content-rate', Yii::app()->createUrl('classes/viewcontent', array("classid" => $data->id))) : '-';
    }

    public static function trainersuggest($data) {
        $tag = '';
        $localitys = '';
        $dataVal = count(ClassCourseTags::model()->findByAttributes(array('users_id' => $data->users_id, 'status' => SkillConfig::STATUS_DEACTIVE)));
        $tag = ($dataVal > 0) ? CHtml::link('Tag', Yii::app()->createUrl('classCourseTags/suggesttag', array("usersid" => $data->users_id,"type"=>'class'))) : '';
        $locality = count(LocalityName::model()->findByAttributes(array('users_id' => $data->users_id, 'status' => SkillConfig::STATUS_DEACTIVE)));
        if ($locality > 0) {
            $localitys = (!empty($locality)) ? CHtml::link('Locality', Yii::app()->createUrl('localityName/suggestlocalityname', array("usersid" => $data->users_id,"type"=>'class'))) : '';
        }
        return (!empty($tag) && !empty($localitys)) ? $localitys . '  /  ' . $tag : $localitys . '' . $tag;
    }

    public static function checkClassesReview($data) {
        $classCourseRatePostitve = ClassCourseTrainnerRate::model()->findByAttributes(array('classes_id' => $data->id));
        $dataVal = Reviews::model()->findByAttributes(array('classes_id' => $data->id));
        return ((!empty($dataVal)) || (!empty($classCourseRatePostitve))) ? CHtml::link('View', Yii::app()->createUrl('reviews/classReviews', array("id" => $data->id))) : 'No Reviews';
    }

    public static function trainerPossitiverate($userType, $model) {
        if ($userType == 'backend') {
            $userstype = 'to_back_user_id';
            $userid = $model->backend_user_id;
        } else {
            $userstype = 'to_front_user_id';
            $userid = $model->users_id;
        }
        $totalclassCourseRateCount = count(ClassCourseTrainnerRate::model()->findAll($userstype . '=' . $userid . ' AND status =' . SkillConfig::STATUS_ACTIVE));
        if (!empty($totalclassCourseRateCount)) {
            $classCourseRatePostitveCount = count(ClassCourseTrainnerRate::model()->findAll($userstype . '=' . $userid));
            return $classCourseRatePostitve = round(($classCourseRatePostitveCount * 100) / $totalclassCourseRateCount);
        }
    }

    public static function trainertotalRate($userType, $model) {
        if ($userType == 'backend') {
            $userstype = 'to_back_user_id';
            $userid = $model->backend_user_id;
        } else {
            $userstype = 'to_front_user_id';
            $userid = $model->users_id;
        }

        return $classCourseRatePostitveCount = count(ClassCourseTrainnerRate::model()->findAll($userstype . '=' . $userid));
    }

    public static function getStartDateByclass($classId) {
        $date = date('Y-m-d');
        $startDate = '';
        $criteria = new CDbCriteria();
        $criteria->condition = ('start_date>="' . $date . '" OR ');
        $criteria->condition .= (('DAYNAME(start_date)>=DAYNAME("' . $date . '" ) AND  schedule_id="' . REPEAT_CLASS_WEEKLY . '" OR '));
        $criteria->condition .= (('DAYOFMONTH(start_date)>=DAYOFMONTH("' . $date . '" ) AND  schedule_id="' . REPEAT_CLASS_MONTHLY . '"'));
        $criteria->addCondition('classes_id="' . $classId . '"');
        $criteria->group = 'classes_id';
        $criteria->order = "DAYOFMONTH(start_date),DAYNAME(start_date),start_date,'ASC'";
        $startDates = ClassBatch::model()->findAll($criteria);
        if (!empty($startDates)) {
            foreach ($startDates as $startDateval) {
                $datestartdate = $startDateval->start_date;
                if ($startDateval->schedule_id == REPEAT_CLASS_MONTHLY) {
                    //if ($startDateval->start_date > $date) {
                    $addThese = 1;
                    $myDateTime = new DateTime($startDateval->start_date);
                    $myDayOfMonth = date_format($myDateTime, 'j');
                    date_modify($myDateTime, "+$addThese months");
                    $myNewDayOfMonth = date_format($myDateTime, 'j');
                    if ($myDayOfMonth > 28 && $myNewDayOfMonth < 4) {
                        date_modify($myDateTime, "-$myNewDayOfMonth days");
                    }
                    $datestartdate = date_format($myDateTime, "Y-m-d");
                    //} else {
                    //  $datestartdate = $startDateval->start_date;
                    //}
                }
                if ($startDateval->schedule_id == REPEAT_CLASS_WEEKLY) {
                    if ($startDateval->start_date > $date) {
                        $datestartdate = $startDateval->start_date;
                    } else {
                        $date = strtotime(date("Y-m-d", strtotime($startDateval->start_date)) . " +1 week");
                        $datestartdate = date("Y-m-d", $date);
                    }
                }
            }

            $startDate .= date('D, d  M', strtotime($datestartdate)) . ' - ';
        }

        if (empty($startDate)) {
            $classcriteria = new CDbCriteria();
            $classcriteria->select = 't.*';
            $classcriteria->join = 'LEFT JOIN skill_class_batch p ON  (t.batche_id = p.id) ';
            $classcriteria->condition = ('t.date>="' . $date . '"  AND t.classes_id=' . $classId);

            $batchSessions = BatcheSession::model()->findAll($classcriteria);
            if (!empty($batchSessions)) {
                foreach ($batchSessions as $batchSession) {
                    $startDate.=date('D, d  M', strtotime($batchSession->date)) . ' -';
                }
            }
        }
        $startDate = substr($startDate, 0, -2);
        if (!empty($startDate)) {
            return $startDate;
        }
    }

}

